﻿using Microsoft.AspNetCore.Cors;
using Newtonsoft.Json.Linq;
using NLog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WTAppletProjectHTTPS.Models;
using WTAppletProjectHTTPS.App_Start;

namespace WTAppletProjectHTTPS.Controllers
{
    [EnableCors("*")]
    public class OpenIDController : ApiController
    {
        private static readonly Logger Logger = NLog.LogManager.GetCurrentClassLogger();
        public string AppId { get; set; } = ConfigurationManager.AppSettings["AppId"];

        public string Secret { get; set; } = ConfigurationManager.AppSettings["Secret"];
        public class OP {
            public string MM { get; set; }
            public string Code { get; set; }
        }
        public class FHClass { 
            public string Name { get; set; }
            public string Phone { get; set; }
            public string Token { get; set; }
        }
        FHClass FHC = new FHClass();
        // POST api/<controller>
        public async Task<HttpResponseMessage> Post([FromBody] OP value)
        {
            ReturnObject RO = new ReturnObject();
            
            if (value.MM != "HSY" + DateTime.Now.ToString("yyyyMMdd"))
            {
                Logger.Error("输入值无效");
                RO.Status = HttpStatusCode.BadRequest;
                RO.Message = "输入值无效";
                RO.Data = null;
                return Request.CreateResponse(HttpStatusCode.BadRequest, RO);
            }
            try
            {
                // 读取响应内容为字符串
                string responseBody = "";
                // 创建一个 HttpClient 实例
                using (HttpClient client = new HttpClient())
                {
                    // 设置请求的 URL
                    string url = $"https://api.weixin.qq.com/sns/jscode2session?appid={AppId}&secret={Secret}&js_code={value.Code}&grant_type=authorization_code";

                    try
                    {
                        // 发送 GET 请求并获取响应
                        HttpResponseMessage response = await client.GetAsync(url);

                        // 确保响应状态码为成功状态
                        response.EnsureSuccessStatusCode();

                        // 读取响应内容为字符串
                        responseBody = await response.Content.ReadAsStringAsync();
                        JObject json = JObject.Parse(responseBody);
                        Task<bool> JG = QueryUser(json["openid"].ToString());
                        if (await JG)
                        {
                            string ToK = TokenManager.GenerateToken(ConfigurationManager.AppSettings["JwtSecret"]);
                            WebApiApplication.TK = ToK;
                            FHC.Token = ToK;
                            RO.Status = HttpStatusCode.OK;
                            RO.Message = "登录成功";
                            RO.Data = FHC;
                            return Request.CreateResponse(HttpStatusCode.OK, RO);
                        }
                        else
                        {
                            RO.Status = HttpStatusCode.NotFound;
                            RO.Message = "您还未注册该小程序账号，请注册后方可使用内部功能";
                            RO.Data = "False";
                            return Request.CreateResponse(HttpStatusCode.NotFound, RO);
                        }
                        
                    }
                    catch (HttpRequestException ex)
                    {
                        Logger.Error("Error:" + ex.Message);
                        RO.Status = HttpStatusCode.InternalServerError;
                        RO.Message = "Error:" + ex.Message;
                        RO.Data = null;
                        return Request.CreateResponse(HttpStatusCode.InternalServerError, RO);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Error:"+ ex.Message);
                RO.Status = HttpStatusCode.InternalServerError;
                RO.Message = "Error:" + ex.Message;
                RO.Data = null;
                return Request.CreateResponse(HttpStatusCode.InternalServerError, RO);
            }
        }

        public async Task<bool> QueryUser(string OpenID)
        {
            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString))
            {
                try
                {
                    await connection.OpenAsync();
                    var query = @"SELECT top 1 AUID, AUUsername, AUPhoneNumber 
                                  FROM AppletUser
                                  WHERE AUOpenID = @OpenID";

                    SqlParameter[] parameters = {
                        new SqlParameter("@OpenID", SqlDbType.NVarChar, 100) { Value = OpenID } 
                    };

                    using (var command = new SqlCommand(query, connection))
                    {
                        command.Parameters.AddRange(parameters);
                        using (var reader = await command.ExecuteReaderAsync())
                        {
                            if (!reader.HasRows)
                            {
                                return false;
                            }

                            var users = new List<AppletUser>();
                            while (await reader.ReadAsync())
                            {
                                users.Add(new AppletUser
                                {
                                    AUID = reader.GetInt32(0),
                                    AUUsername = reader.GetString(1),                                    
                                    AUPhoneNumber = reader.GetString(2)  
                                });
                            }

                            if (users.Count > 0)
                            {
                                FHC.Name = users[0].AUUsername;
                                FHC.Phone = users[0].AUPhoneNumber;
                                return true;
                            }
                            else
                            {
                                return false;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {

                    return false;
                }
            }
        }
    }
}